package com.sboot.shiro.biz.sys.user.controller;

import javax.servlet.http.HttpSession;

import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.IncorrectCredentialsException;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.subject.Subject;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import com.sboot.shiro.biz.sys.user.po.SysUser;
import com.sboot.shiro.common.beans.ReturnData;

@Controller
public class LoginController {

	private static final Logger logger = LoggerFactory.getLogger(LoginController.class);
	
	@RequestMapping(value = "/login", method = { RequestMethod.GET })
	public String login() {
		return "login";
	}

	@ResponseBody
	@RequestMapping(value = "/doLogin", method = { RequestMethod.POST })
	public ReturnData doLogin(String userName, String password, HttpSession session, ModelMap modelMap) {
		UsernamePasswordToken usernamePasswordToken = new UsernamePasswordToken(userName, password);
		Subject subject = SecurityUtils.getSubject();
		try {
			subject.login(usernamePasswordToken);
			SysUser user = (SysUser) subject.getPrincipal();
			session.setAttribute("user", user);
			modelMap.addAttribute("msg", "登录成功");
			return ReturnData.SUCCESS("登录成功", null);
		} catch (IncorrectCredentialsException e) {
			modelMap.addAttribute("msg", "账号或密码不正确");
			logger.error("账号或密码不正确", e);
			return ReturnData.FAIL("账号或密码不正确", null);
		} catch (Exception e) {
			modelMap.addAttribute("msg", e.getMessage());
			logger.error(e.getMessage(), e);
			return ReturnData.FAIL(e.getMessage(), null);
		}
	}

	@RequestMapping("/logout")
	public String logout() {
		Subject subject = SecurityUtils.getSubject();
		subject.logout();
		return "redirect:login";
	}

	@RequestMapping("/index")
	public String index() {
		return "index";
	}
	
	@RequestMapping("/")
	public String idx() {
		return "index";
	}
}
